from .common import *

class ViewGeneratorPage3(wx.adv.WizardPage):
    '''个性化创建视图【第三页】'''
    def __init__(self, parent, title='第三步：代码预览与调整', out_data = None):
        WizardPageSimple.__init__(self, parent)
        self.next = self.prev = None
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(self.sizer)
        if out_data is not None:
            self.out_data = out_data
            if VIEWS_WIZARD_CONTEXT not in self.out_data:
                self.out_data[VIEWS_WIZARD_CONTEXT] = {}
            self.context = self.out_data[VIEWS_WIZARD_CONTEXT]
            self.context['3'] = {}
            self.context = self.context['3']
        else:
            raise Exception('没有上下文，无法开启向导页面')

        self.args = {} # 除了 view_name 外的所有替换参数键值对
        self.code = ""

        self._init_UI(title)
        self._init_listener()

    def _init_UI(self, title):
        '''初始化界面布局'''
        '''
            设置当前页标题
        '''
        title = wx.StaticText(self, -1, title)
        title.SetFont(wx.Font(16, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD))
        self.sizer.Add(title, 0, wx.ALIGN_LEFT|wx.ALL, 3)
        self.sizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND|wx.ALL, 5) # 水平分割线

        '''
            替换输入框与按钮
        '''
        self.choiceReplace = wx.Choice(self, -1, choices=[], size=(120, -1))
        self.inputReplace = wx.TextCtrl(self, -1, value='', size=(340, -1))
        ### 界面变动值
        self.choiceReplaceFuncs = wx.Choice(self, -1, choices=[], size=(340, -1))
        self.choiceReplaceFuncs.Show(False)
        self.checkBoxReplace = wx.CheckBox(self, -1, label = '系统预置值') # 后触发型
        ### 
        self.btn_replace = buttons.GenButton(self, -1, label='替换')
        self.btn_replace.SetBackgroundColour(CON_COLOR_MAIN)
        self.btn_replace.SetForegroundColour(CON_COLOR_PURE_WHITE)
        
        self.flexGridSizer = wx.FlexGridSizer(cols=4, hgap=1, vgap=0)
        self.sizer.Add(self.flexGridSizer, 0, wx.EXPAND | wx.ALL, 1)
        self.flexGridSizer.AddGrowableCol(3)

        self.flexGridSizer.Add(self.choiceReplace, 0, wx.EXPAND)
        self.flexGridSizer.Add(self.inputReplace, 0, wx.EXPAND)
        self.flexGridSizer.Add(self.checkBoxReplace, 0, wx.EXPAND)
        self.flexGridSizer.Add(self.btn_replace, 0, wx.EXPAND)

        '''
            所有的其他控件全部放在滚动面板中
        '''
        self.editorPanel = PythonEditor(self)
        self.sizer.Add(self.editorPanel, 1, wx.EXPAND | wx.ALL, 1)

    def _init_listener(self):
        """注册监听"""
        self.Bind(wx.EVT_CHECKBOX, self.onCheckBoxReplace, self.checkBoxReplace)
        self.Bind(wx.adv.EVT_WIZARD_PAGE_CHANGING, self.onWizPageChanging)
        self.Bind(wx.adv.EVT_WIZARD_CANCEL, self.onWizCancel)

        self.Bind(wx.EVT_CHOICE, self.onChoiceReplace, self.choiceReplace)
        self.Bind(wx.EVT_BUTTON, self.onBtnReplace, self.btn_replace)

    def onBtnReplace(self, evt):
        """替换按钮点击事件"""
        replace_arg = self.choiceReplace.GetString(self.choiceReplace.GetSelection()).strip()
        input_value = self.inputReplace.GetValue().strip()
        choice_value = self.choiceReplaceFuncs.GetString(self.choiceReplaceFuncs.GetSelection()).strip()
        isChoice = self.checkBoxReplace.IsChecked()

        if not replace_arg:
            RichMsgDialog.showOkMsgDialog(self, "请先选择替换参数！", "错误")
            return

        if isChoice:
            if not choice_value:
                RichMsgDialog.showOkMsgDialog(self, "下拉框空值无法进行替换，若想赋空值，请切换到输入框", "错误")
                return
            self.args[replace_arg] = choice_value
        else:
            self.args[replace_arg] = input_value

        self._update_code()

    def _update_code(self):
        """根据替换参数更新代码"""
        code = retools.patt_template_replace(retools.PATT_REPLACE, self.code, **self.args)
        self.editorPanel.SetText(code)
        self.editorPanel.EmptyUndoBuffer()
        self.editorPanel.Colourise(0, -1)

    def onChoiceReplace(self, evt):
        """替换参数选择后，可选择值更新"""
        self.choiceReplaceFuncs.Clear()
        arg = evt.GetString()
        self.choiceReplaceFuncs.Append("")
        for _ in view_type_data.get_replace_args_by_replace_name(arg):
            self.choiceReplaceFuncs.Append(_)

    def onWizCancel(self, evt):
        """界面取消时触发"""
        if not RichMsgDialog.showYesNoMsgDialog(self, '【取消】/【关闭】将导致已填的数据全部被丢弃！', "警告"):
            evt.Veto()

    def onCheckBoxReplace(self, evt):
        """切换输入值的方式"""
        self.flexGridSizer.Clear()
        self.flexGridSizer.Add(self.choiceReplace, 0, wx.EXPAND)
        if evt.IsChecked():
            self.flexGridSizer.Add(self.choiceReplaceFuncs, 0, wx.EXPAND)
            self.choiceReplaceFuncs.Show(True)
            self.inputReplace.Show(False)
        else:
            self.flexGridSizer.Add(self.inputReplace, 0, wx.EXPAND)
            self.choiceReplaceFuncs.Show(False)
            self.inputReplace.Show(True)
        self.flexGridSizer.Add(self.checkBoxReplace, 0, wx.EXPAND)
        self.flexGridSizer.Add(self.btn_replace, 0, wx.EXPAND)
        self.Layout()

    def onWizPageChanging(self, evt):
        """向导页切换时触发"""
        # evt.Veto()
        # 各式数据留存
        temp_data = self.editorPanel.GetValue()

        # 检测是否还有未替换数据
        replaces = retools.PATT_REPLACE.findall(temp_data)
        if len(replaces) > 0:
            RichMsgDialog.showOkMsgDialog(self, '、'.join(replaces)+' 未替换！', "警告")

        self.context['code'] = temp_data

    def SetNext(self, next):
        '''设置后一页'''
        self.next = next

    def SetPrev(self, prev):
        '''设置前一页'''
        self.prev = prev

    def GetNext(self):
        '''获取下一页/下一指定页'''
        '''
            通过前几个向导页的数据，初始化当前数据
        '''
        if not self.code:
            # 初次进入时更新
            context1 = self.out_data[VIEWS_WIZARD_CONTEXT]["1"]
            if 'view_name' in context1 and 'view_type_name' in context1:
                view_name = context1['view_name']
                view_type_name = context1['view_type_name']
                code = view_type_data.get_view_data_by_name(view_type_name)
                self.code = retools.patt_template_replace(retools.PATT_REPLACE, code, view_name=view_name)

                self.editorPanel.SetText(self.code)
                self.editorPanel.EmptyUndoBuffer()
                self.editorPanel.Colourise(0, -1)

                self.choiceReplace.Clear()
                self.choiceReplace.Append("")
                for _ in retools.PATT_REPLACE.findall(self.code):
                    self.choiceReplace.Append(_)
            
        return self.next

    def GetPrev(self):
        '''获取上一页/上一指定页'''
        return self.prev

